import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import time
import matplotlib

from matplotlib.font_manager import *  # 如果想在图上显示中文，需导入这个包
from matplotlib import cm
from datetime import datetime
from scipy.stats import boxcox

path = r""
df2 = pd.read_csv(path, sep=',', usecols=[4, 7, 8])

df2['month'] = pd.to_datetime(df2['StrTime']).dt.month

month_counts = df2['month'].value_counts().sort_index()

scaled_sizes = month_counts * 0.08

# 预设字体格式，并传给rc方法
font = {'family': 'SimHei', "size": 24}
matplotlib.rc('font', **font)  # 一次定义终身使用

# 绘制散点图


plt.figure(facecolor='white')

plt.title('图1：每月消息数量趋势', fontsize=22)

plt.xlabel('月份', fontsize=20)
plt.ylabel('消息数量', fontsize=20)
plt.xticks(range(1, 13), fontsize=15)
plt.yticks(fontsize=15)

plt.scatter(month_counts.index, month_counts.values, color='#80BCBD', marker='o')

plt.grid(True, linestyle='solid', linewidth=1, color='lightgrey', axis='y')

fig = plt.gcf()
fig.set_size_inches(15, 8)
fig.savefig('chat_month.png', dpi=100)

plt.show()

df2['month_bobo'] = pd.to_datetime(df2[df2['IsSender'] == 1]['StrTime']).dt.month
df2['month_pupu'] = pd.to_datetime(df2[df2['IsSender'] == 0]['StrTime']).dt.month

labels = ['Mo', 'Sheng']
colors = ['#FFC0D9', '#8ACDD7']

month_counts_bobo = df2['month_bobo'].value_counts().sort_index()
month_counts_pupu = df2['month_pupu'].value_counts().sort_index()

# 找到PUPU和BOBO每个月的最大值和对应的月份
max_bobo = month_counts_bobo.max()
max_month_bobo = month_counts_bobo.idxmax()

max_pupu = month_counts_pupu.max()
max_month_pupu = month_counts_pupu.idxmax()

month_counts_pupu.plot(kind='line', marker='o', label='PUPU', color='#FFC0D9')
month_counts_bobo.plot(kind='line', marker='o', label='BOBO', color='#8ACDD7')

# 在最高点上添加标签
plt.annotate(f'Max: {max_pupu}', xy=(max_month_pupu, max_pupu), xytext=(max_month_pupu + 0.5, max_pupu + 10),
             arrowprops=dict(facecolor='black', arrowstyle='->'),
             fontsize=18)

plt.annotate(f'Max: {max_bobo}', xy=(max_month_bobo, max_bobo), xytext=(max_month_bobo + 0.4, max_bobo + 10),
             arrowprops=dict(facecolor='black', arrowstyle='->'),
             fontsize=18)

plt.title('图2：每月消息数趋势', fontsize=22)

plt.xlabel('月份', fontsize=20)
plt.ylabel('消息数', fontsize=20)
plt.xticks(range(1, 13), fontsize=15)
plt.yticks(fontsize=15)

plt.grid(True, linestyle='solid', linewidth=0.5, color='lightgrey')


plt.legend(labels, loc="best")

plt.tight_layout()  # 优化布局，确保标签和标题不重叠

fig = plt.gcf()
fig.set_size_inches(15, 8)
fig.savefig('chat_plot.png', dpi=100)
plt.show()

# 图3

value_counts = df2['IsSender'].value_counts()

# 计算百分比
percentages = 100. * value_counts / value_counts.sum()

# 创建饼图
labels = ['Mo', 'Sheng']
colors = ['#FFC0D9', '#8ACDD7']
explode = (0.1, 0)  # 突出显示第一个切片

plt.figure(figsize=(8, 8))


# 定义格式化函数，用于在饼图内部显示数据
def func(pct, allvals):
    absolute = int(pct / 100. * np.sum(allvals))
    return f"{pct:.1f}%\n({absolute:d})"


plt.pie(value_counts, explode=explode, labels=labels, colors=colors,
        autopct=lambda pct: func(pct, value_counts), shadow=True, startangle=80,
        textprops={'style': 'italic', 'fontsize': 18})

plt.title('图 3: 信息量饼图', fontsize=22)

plt.legend(labels, loc="best")
plt.axis('equal')  # 使饼图保持圆形

fig = plt.gcf()
fig.set_size_inches(15, 8)
fig.savefig('chat_pie', dpi=100)
plt.show()

# 图四
dates = pd.to_datetime(df2['StrTime'])
weekdays = dates.dt.day_name()

weekday_counts = weekdays.value_counts()

# 绘制饼图

colors = ['#FF90BC', '#FFC0D9', '#F9F9E0', '#8ACDD7', '#EEE7DA', '#88AB8E', '#AFC8AD']
explode = (0.1, 0, 0, 0, 0, 0, 0)  # 突出显示第一个切片
plt.figure(figsize=(8, 8))

plt.pie(weekday_counts, explode=explode, labels=weekday_counts.index, colors=colors, autopct='%1.1f%%', shadow=True,
        startangle=90, textprops={'fontsize': 18})
plt.title('图4：一周内消息的分布', fontsize=22)

plt.legend(labels=weekday_counts.index, loc="best")
plt.axis('equal')  # 使饼图保持圆形

fig = plt.gcf()
fig.set_size_inches(15, 8)
fig.savefig('chat_pie_2', dpi=100)
plt.show()


# 图 5
df2['Date'] = pd.to_datetime(df2['StrTime'])
df2['Month'] = df2['Date'].dt.month  # 提取月份

# 使用pivot_table创建矩阵，按月份和日期
heatmap_data = df2.pivot_table(index=df2['Date'].dt.day, columns='Month', values='StrTime', aggfunc='count')

# 使用seaborn绘制热力图
sns.heatmap(heatmap_data, cmap="GnBu", linewidths=0.5, linecolor='gray')

plt.title('图 5: 月度聊天热力图', fontsize=22)
plt.xlabel('月', fontsize=20)
plt.ylabel('日', fontsize=20)
plt.xticks(fontsize=15)  # 设置x轴标签
plt.yticks(fontsize=15)
plt.tight_layout()

fig = plt.gcf()
fig.set_size_inches(15, 8)
fig.savefig('heatmap_2.png', dpi=100)
plt.show()

# 图6

df2['hour'] = pd.to_datetime(df2['StrTime']).dt.hour

plt.title('图6：一天中的消息分布', fontsize=18)
plt.xlabel('时间', fontsize=18)
plt.ylabel('消息数', fontsize=18)

sns.set_style('darkgrid')  # 设置图片为深色背景且有网格线

sns.histplot(df2['hour'], bins=24, kde=True, color='lightcoral')

plt.xticks(np.arange(0, 25, 1.0), fontsize=15)
plt.yticks(fontsize=15)

fig = plt.gcf()
fig.set_size_inches(15, 8)
fig.savefig('chat_time.png', dpi=100)
plt.show()